package com.example.demo.sms;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;

import java.io.IOException;
public class sendMessage {
    /**
     * 生成6位数字验证码
     *
     * @return 验证码
     */
    public static String vcode()
    {
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (Math.random() * 9);
        }
        return vcode;
    }

    public String getPhoneMessage(String phone)
    {
        int appid = 1400425977;
        String appkey = "520362850b8a901ef00e6bcfa18180bc";
        String[] phoneNumbers = {phone}; //手机号可以添很多。
        int templateId = 727797;
        String code = vcode();
        String smsSign = "快易需求系统";
        try {
            String[] params = {code,"5"};  //第一个参数传递{1}位置想要的内容，第二个传递{2}的内容，以此类推。具体看步骤5
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    templateId, params, smsSign, "", "");
            System.out.println(result);
        } catch (HTTPException | JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }

    public static String sendSMS(String phone)    //给number 发短信，返回验证码
    {
        sendMessage phoneCode = new sendMessage();
        return phoneCode.getPhoneMessage(phone);
    }
}

